import 'dart:async';
import 'dart:io';

import 'package:amway_superapp_creator_plugin/analysis/zhuge_edit.dart';
import 'package:amway_superapp_creator_plugin/config/enum_config.dart';
import 'package:amway_superapp_creator_plugin/models/cover_images_model.dart';
import 'package:amway_superapp_creator_plugin/models/create_user_info_model.dart';
import 'package:amway_superapp_creator_plugin/models/guanfang_image.dart';
import 'package:amway_superapp_creator_plugin/net/http_manager.dart';
import 'package:amway_superapp_creator_plugin/utils/oss_util.dart';
import 'package:amway_superapp_creator_plugin/utils/toast_util.dart';
import 'package:amway_superapp_creator_plugin/viewmodels/base_model.dart';
import 'package:collection/equality.dart';
import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_flavor/flutter_flavor.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';

import '../../api.dart';

class SetCoverModel extends BaseModel {
  SetCoverModel({@required Api api}) : super(api: api);

  List<CoverImagesModel> _datas = []; //官网封面

  List<CoverImagesModel> get datas => _datas;

  List<CoverImagesModel> _checkImagesDatas = []; //选中封面

  List<CoverImagesModel> get checkImagesDatas => _checkImagesDatas;

  List<CoverImagesModel> sourceCoverDatas = []; //用户保存数据
  bool isDayFirstJoin = true;

  void getIsFirstJoin(var amwayAda) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var dateStr = DateUtil.getNowDateStr();
    isDayFirstJoin = prefs.getBool(amwayAda +
            DateUtil.formatDate(DateUtil.getDateTime(dateStr),
                format: 'yyyy-MM-dd')) ??
        true;
    notifyListeners();
  }

  bool isAuditfailed = false;
  int failednum = 0;

  ///
  /// 初始化用户数据
  void initUserCovers(List<ImagesBean> covers) {
    if (null != covers && covers.length > 0) {
      covers.forEach((imagesBean) {
        print(imagesBean.state);
        sourceCoverDatas.add(CoverImagesModel(
          path: imagesBean.data,
          state: imagesBean.state,
          officialFlag: imagesBean.officialFlag,
        ));
        checkImagesDatas.add(CoverImagesModel(
          path: imagesBean.data,
          state: imagesBean.state,
          officialFlag: imagesBean.officialFlag,
        ));
      });
      covers.forEach((imagesBean) {
        if (imagesBean.officialFlag == "NO" && imagesBean.state == 3) {
          isAuditfailed = true;
          failednum++;
        }
      });

      notifyListeners();
    }
  }

  int selAlbumCount = 0;
  AssetEntity assetEntity;

  bool checkitemIsFaild(int index) {
    var bean = checkImagesDatas[index];
    if (bean.officialFlag == 'NO' && bean.state == 3) {
      return true;
    }
    return false;
  }

  bool initChecks(int index) {
    bool isCheck = false;
    if (null != checkImagesDatas && checkImagesDatas.length > 0) {
      for (var c in checkImagesDatas) {
        if (c.data == datas[index].data) {
          isCheck = true;
          break;
        }
      }
    }
    return isCheck;
  }

  void initAlbumSelSize() {
    selAlbumCount = 0;
    if (null != checkImagesDatas && checkImagesDatas.length > 0) {
      checkImagesDatas.forEach((element) {
        if (element.officialFlag == "NO") {
          selAlbumCount++;
          assetEntity = element.assetEntity;
        }
      });
    }
    notifyListeners();
  }

  /// 检测是否首次进入
  void setFirstJoin({bool value, String amwayAda}) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var dateStr = DateUtil.getNowDateStr();
    prefs.setBool(
        amwayAda +
            DateUtil.formatDate(DateUtil.getDateTime(dateStr),
                format: 'yyyy-MM-dd'),
        value);
    isDayFirstJoin = value;
    notifyListeners();
  }

  set checkImagesDatas(List<CoverImagesModel> value) {
    _checkImagesDatas = value;
    notifyListeners();
  }

  /// 初始化封面数据
  Future<void> initDatas(String amwayAda) async {
    getIsFirstJoin(amwayAda);

/*
    datas.add(CoverImagesModel(
        officialFlag: "YES",
        path:
            "https://weiliicimg1.pstatp.com/weili/lp/903338910689525788.webp"));
    datas.add(CoverImagesModel(
        officialFlag: "YES",
        path:
            "https://weiliicimg9.pstatp.com/weili/lp/600003581240148011.webp"));
    datas.add(CoverImagesModel(
        officialFlag: "YES",
        path:
            "https://icweiliimg6.pstatp.com/weili/lp/904646934384214041.webp"));
    datas.add(CoverImagesModel(
        officialFlag: "YES",
        path:
            "https://icweiliimg9.pstatp.com/weili/lp/918291143544274962.webp"));

    if (checkImagesDatas.length <= 0) {
      checkImagesDatas.add(datas.first);
      sourceCoverDatas.add(datas.first);
    }
    notifyListeners();*/

    var queryParameters = {
      "q": "官方封面",
      "start": 0,
      "rows": 100,
      "sort": "-publishdate"
    };
    var uuid = Uuid();
    // Generate a v1 (time-based) id
    var v1 = uuid.v1();
    var heards = {
      "Authorization": FlavorConfig.instance.variables["AppCode"],
      "X-Ca-Nonce": v1,
    };
    var amwayBaseUrl = FlavorConfig.instance.variables["amwayBaseUrl"];
    Options options = Options(headers: heards);
    Dio dio = Dio();
    try {
      Response response = await dio.get(amwayBaseUrl + "/images",
          queryParameters: queryParameters, options: options);
      if (response.statusCode == 200) {
        List<GuanfangImage> guanfangImages = [];
        response.data.forEach((element) {
          guanfangImages.add(GuanfangImage.fromJson(element));
        });
        if (guanfangImages.isNotEmpty) {
          guanfangImages.forEach((guanFangImage) {
            datas.add(
                CoverImagesModel(path: guanFangImage.url, officialFlag: "YES"));
          });
          if (checkImagesDatas.length <= 0) {
            checkImagesDatas.add(datas.first);
            sourceCoverDatas.add(datas.first);
          }
          notifyListeners();
        }
      } else {
        print(response.statusCode);
      }
    } catch (e) {
      print(e);
    }
  }

  void addDatas(String path) {
    datas.add(CoverImagesModel(path: path));
    notifyListeners();
  }

  void addLocaDatas(List<AssetEntity> datas) {
    datas.forEach((assetEntity) {
      var coverImagesModel = CoverImagesModel(
          assetEntity: assetEntity,
          officialFlag: EnumUtils.enumToString(OfficialFlag.NO));
      checkImagesDatas.add(coverImagesModel);
    });

    initAlbumSelSize();
    notifyListeners();
  }

  void removefailure() {
    isAuditfailed = false;
    failednum = 0;
    if (checkImagesDatas.length > 0)
      for (int i = 0; i < checkImagesDatas.length; i++) {
        if (checkImagesDatas[i].state == 3) {
          checkImagesDatas.removeAt(i);
        }
      }
    notifyListeners();
  }

  void removeSelImage(CoverImagesModel coverImagesModel) {
    checkImagesDatas.remove(coverImagesModel);
    notifyListeners();
    initAlbumSelSize();
  }

  void checkSelImageSource(CoverImagesModel scoverImagesModel) {
    bool isRemove = false;
    for (int i = 0; i < checkImagesDatas.length; i++) {
      var coverImagesModel = checkImagesDatas[i];
      if (coverImagesModel.officialFlag == "YES" &&
          coverImagesModel.data == scoverImagesModel.data) {
        checkImagesDatas.remove(coverImagesModel);
        isRemove = true;
        break;
      }
    }
    if (!isRemove) {
      if (checkImagesDatas.length < 3) {
        checkImagesDatas.add(scoverImagesModel);
      } else {
        ToastUtils.showShortToast("最多只能选择3张封面图哦");
      }
    }
    notifyListeners();
  }

  void checkSelNetImage(CoverImagesModel scoverImagesModel) {
    for (int i = 0; i < checkImagesDatas.length; i++) {
      var coverImagesModel = checkImagesDatas[i];
      if (coverImagesModel.officialFlag == "YES" &&
          coverImagesModel.data == scoverImagesModel.data) {
        checkImagesDatas.remove(coverImagesModel);
      }
    }
    notifyListeners();
  }

  bool checkUpdateState() {
    if (checkImagesDatas.length != sourceCoverDatas.length) {
      return false;
    }

    Function deepEq = const DeepCollectionEquality().equals;

    return deepEq(sourceCoverDatas, checkImagesDatas); // => true
  }

  ///上传图片
  void uploadMultiImages(
      List<CoverImagesModel> mCoverImagesModels, HttpSuccessCallback callback) {
    List<ImagesBean> resultPaths = new List();
    List<AssetEntity> assetEntityList = new List();

    mCoverImagesModels.forEach((element) {
      if (element.officialFlag == "YES") {
        resultPaths.add(ImagesBean(
            data: element.data,
            dataType: EnumUtils.enumToString(DataType.IMAGE),
            officialFlag: EnumUtils.enumToString(OfficialFlag.YES)));
      } else {
        if (element.assetEntity == null && element.data != null) {
          resultPaths.add(ImagesBean(
              data: element.data,
              dataType: EnumUtils.enumToString(DataType.IMAGE),
              officialFlag: EnumUtils.enumToString(OfficialFlag.NO)));
        } else {
          assetEntityList.add(element.assetEntity);
        }
      }
    });

    List<Future<String>> uploadQueue = new List();
    assetEntityList.forEach((element) {
      uploadQueue.add(uploadSingleImage(element.file));
    });

    Future.wait(uploadQueue)
        .then((results) {
          // print(results[0].toString()+results[1]);
          for (int i = 0; i < results.length; i++) {
            resultPaths.add(ImagesBean(
                data: results[i],
                no: i,
                dataType: EnumUtils.enumToString(DataType.IMAGE),
                officialFlag: EnumUtils.enumToString(OfficialFlag.NO)));
          }
          if (null != callback) {
            callback.call(resultPaths);
            ZhugeEditAnalysis.editCoverClickSave("封面上传", true);
          }
        })
        .catchError((e) {
          ZhugeEditAnalysis.editCoverClickSave("封面上传", false);
        })
        .whenComplete(() {})
        .asStream();
  }

  Future<String> uploadSingleImage(Future<File> future) async {
    String path = await OssHelper.getOssConfiguration().then((result) {
      Map<String, dynamic> ossMsg = {
        "accessKeyId": result.data['data']['accessKeyId'],
        "accessKeySecret": result.data['data']['accessKeySecret'],
        "expiration": result.data['data']['expiration'],
        "securityToken": result.data['data']['securityToken']
      };
      return ossMsg;
    }).then((oss) => singleUploadImageWithConfig(future, oss));
    return path;
  }

  Future<String> singleUploadImageWithConfig(
      Future<File> file, Map<String, dynamic> ossMsg) async {
    String path = await file.then((f) => OssHelper.uploadToOss(f, ossMsg));
    return path;
  }
}
